#include "DirectXDevice.h"

DirectXDevice::DirectXDevice (void)
{
	ClearColor = D3DCOLOR_RGBA(0, 0, 0, 0);
}

DirectXDevice::~DirectXDevice (void)
{
	CleanD3D();
	DestroyWindow(hWnd);
	UnregisterClass(L"Engine", hInstance);
}

BOOL DirectXDevice::Init (HINSTANCE hInst, LPCWSTR WinTitle, UINT ScrnWidth,
						  UINT ScrnHeight, UINT ClrDepth, BOOL Fullscreen)
{
	BOOL Success = TRUE;

	hInstance = hInst;
	WindowTitle = WinTitle;
	ScreenWidth = ScrnWidth;
	ScreenHeight = ScrnHeight;
	ColorDepth = ClrDepth;
	FullScreen = Fullscreen;
	
	Success = InitWindow();
	DisplayWindow();
	InitD3D();

	return Success;
}

void DirectXDevice::BeginRendering (void)
{
	Clear();
	d3ddev->BeginScene();
}

void DirectXDevice::EndRendering (void)
{
	d3ddev->EndScene();
	d3ddev->Present(NULL, NULL, NULL, NULL);
}

void DirectXDevice::Clear (void)
{
	d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, ClearColor, 1.0f, 0);
	d3ddev->Clear(0, NULL, D3DCLEAR_ZBUFFER, ClearColor, 1.0f, 0);
}

void DirectXDevice::SetClearColor (int Red, int Green, int Blue, int Alpha)
{
	ClearColor = D3DCOLOR_RGBA(Red, Green, Blue, Alpha);
}


void* DirectXDevice::GetDrawDevice (void)
{
	return d3ddev;
}

void DirectXDevice::InitD3D (void)
{
	//DirectX Initialization
	d3d = Direct3DCreate9(D3D_SDK_VERSION);
	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory(&d3dpp, sizeof(d3dpp));
	d3dpp.Windowed = !FullScreen;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.hDeviceWindow = hWnd;
	d3dpp.EnableAutoDepthStencil = TRUE;
	d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
	if (FullScreen == TRUE)
	{
		d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
		d3dpp.BackBufferWidth = ScreenWidth;
		d3dpp.BackBufferHeight = ScreenHeight;
	}
	d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
					  D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev);
	d3ddev->SetRenderState(D3DRS_LIGHTING, FALSE);
	d3ddev->SetRenderState(D3DRS_ZENABLE, TRUE);
}

void DirectXDevice::CleanD3D (void)
{
	if (d3ddev)
		d3ddev->Release();
	if (d3d)
		d3d->Release();
	DestroyWindow(hWnd);
	UnregisterClass(L"Engine", hInstance);
}